package com.cxs.musicplaywidget.view.list;

import com.cxs.musicplaywidget.ResourceTable;
import com.cxs.musicplaywidget.player.data.MusicInfo;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ListProvider
 * @Author cxs
 * @Version 1.0
 * @Description TODO
 * @Date 2022/03/16
 */
public class ListItemProvider extends BaseItemProvider {
    List<MusicInfo> playList = new ArrayList<>();
    private int playIndex;

    public ListItemProvider() {
    }

    public ListItemProvider(List<MusicInfo> playList) {
        this.playList = playList;
    }

    public void setPlayList(List<MusicInfo> playList, int playIndex) {
        this.playList = playList;
        this.playIndex = playIndex;
    }

    @Override
    public int getCount() {
        if (playList == null) {
            return 0;
        }
        return playList.size();
    }

    @Override
    public Object getItem(int i) {
        if (playList.isEmpty() || i >= playList.size() || i < 0) {
            return null;
        }
        return playList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        Component cpt = component;
        ViewHolder viewHolder;
        if (cpt == null) {
            cpt = LayoutScatter.getInstance(componentContainer.getContext())
                    .parse(ResourceTable.Layout_play_list_item, null, false);
            viewHolder = new ViewHolder(cpt);
            cpt.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) cpt.getTag();
        }

        MusicInfo musicInfo = playList.get(i);
        if (musicInfo.getIndex() == playIndex) {
            cpt.setBackground(new ShapeElement(componentContainer.getContext(), ResourceTable.Graphic_background_play_list_selected));
        }
        viewHolder.title.setText(musicInfo.getTitle());
        viewHolder.artist.setText(musicInfo.getArtist());
        viewHolder.duration.setText(musicInfo.getDuration());

        return cpt;
    }

    private static class ViewHolder {
        private Text title;
        private Text artist;
        private Text duration;
        private Button state;

        public ViewHolder(Component component) {
            title = component.findComponentById(ResourceTable.Id_music_title);
            artist = component.findComponentById(ResourceTable.Id_music_artist);
            duration = component.findComponentById(ResourceTable.Id_music_duration);
            state = component.findComponentById(ResourceTable.Id_btn_play_state);
        }
    }
}
